#include "clienttcp.h"
#include "ui_clienttcp.h"

ClientTcp::ClientTcp(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::ClientTcp)
{
    ui->setupUi(this);
    //关联连接成功的信号
    connect(&msocket,&QTcpSocket::connected,this,&ClientTcp::connect_suc);
    //设置发送按钮失效
    ui->sendBt->setEnabled(false);

    //当与服务器端口连接的时候会发送disconnected信号
    connect(&msocket,&QTcpSocket::disconnected,this,&ClientTcp::connect_dis);

    //当客户端有数据可读(服务器发送数据过来了）会发送readyRead信号
    connect(&msocket,&QTcpSocket::readyRead,this,&ClientTcp::read_data);




}

ClientTcp::~ClientTcp()
{
    delete ui;
}

void ClientTcp::on_connectBt_clicked()
{
    QString ip = ui->ipEdit->text();
    QString port = ui->portEdit->text();
    msocket.connectToHost(ip,port.toUShort());  //当连接成功会发送connected信号
}

//当客户端连接成功调用的槽函数
void ClientTcp::connect_suc()
{
    //设置发送按钮生效
    ui->sendBt->setEnabled(true);
}

//当与服务器断开连接会调用的槽函数
void ClientTcp::connect_dis()
{
    //设置发送按钮失效
    ui->sendBt->setEnabled(false);
}

//当服务器发送数据会调用槽函数
void ClientTcp::read_data()
{
    QString data = msocket.readAll();
    //服务器发送的客户id列表id-12312321:565655353:56456454
    if(data.startsWith("id-"))
    {
        //删除id-
        data.remove("id-");
        QStringList list = data.split(":");

        ui->listWidget->clear();
        ui->listWidget->addItems(list);
        return;
    }

    //服务器转发的客户端数据msg


    ui->textBrowser->append(data);
}


void ClientTcp::on_sendBt_clicked()
{
    //发送数据到服务器
    QString data = ui->textEdit->toPlainText();

    QString id = ui->listWidget->currentItem()->text();
    data.push_front(id+"-");

    msocket.write(data.toUtf8());
}

void ClientTcp::on_clearBt_clicked()
{
    ui->textBrowser->clear();
    ui->textEdit->clear();
}
